package com.zlc.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zlc.common.constant.ProductConstant;
import com.zlc.common.to.HasStockVo;
import com.zlc.common.to.SkuReductionTo;
import com.zlc.common.to.SpuBoundsTo;
import com.zlc.common.to.es.SkuEsModel;
import com.zlc.common.utils.R;
import com.zlc.gulimall.product.dao.SpuInfoDescDao;
import com.zlc.gulimall.product.entity.*;
import com.zlc.gulimall.product.feign.CouponFeignService;
import com.zlc.gulimall.product.feign.SearchFeignService;
import com.zlc.gulimall.product.feign.WareFeignService;
import com.zlc.gulimall.product.service.*;
import com.zlc.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlc.common.utils.PageUtils;
import com.zlc.common.utils.Query;

import com.zlc.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    //实际上你不应该在serviceimpl这里引入dao层的东西，应该引入的是其他的serviceimp,这里偷懒了就只引入了dao
    @Resource
    private SpuInfoDescDao spuInfoDescDao;

    @Resource
    private SpuImagesService spuImagesService;

    @Resource
    private ProductAttrValueService productAttrValueService;

    @Resource
    private SkuInfoService skuInfoService;

    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    private CouponFeignService couponFeignService;

    @Resource
    private BrandService brandService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private AttrService attrService;

    @Resource
    private WareFeignService wareFeignService;

    @Resource
    private SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

//    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1.spu基本信息   pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();

        //2.spu描述信息   pms_spu_info_desc    这个描述是用图片描述的
        List<String> decripts = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //使用,分割descripts后，将其变成字符串封装
        spuInfoDescEntity.setDecript(String.join(",",decripts));
        spuInfoDescDao.insert(spuInfoDescEntity);

        //3.spu图片集     pms_spu_images
        List<String> spuImages = spuSaveVo.getImages();
        spuImagesService.saveImages(spuImages,spuId);

        //4.spu规格参数   pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        productAttrValueService.saveProductAttrValue(baseAttrs,spuId);

        //5.spu积分信息   sms -> sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds,spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);
        R r1 = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r1.getCode() != 0){
            log.info("feign--SaveBounds远程调用失败!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`");
        }

        //6.spu对应的所有sku信息
        //6.1) sku基本信息   pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if(skus != null && skus.size() > 0){
            skus.forEach((item) -> {
                String defaultImage = "";
                List<Images> images = item.getImages();
                for (Images image : images) {
                    if(image.getDefaultImg() == 1){
                        defaultImage = image.getImgUrl();

                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
                skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                //设置默认图片
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.save(skuInfoEntity);

                //6.2) sku图片信息   pms_sku_images
                List<SkuImagesEntity> collect = images.stream().map(i -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(i.getImgUrl());
                    skuImagesEntity.setDefaultImg(i.getDefaultImg());
                    return skuImagesEntity;
                }).filter(skuImagesEntity -> {
                    //返回ture就是需要 ，返回false则被过滤
                    return !StringUtils.isEmpty(skuImagesEntity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(collect);

                //6.3) sku销售属性   pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                //6.4) sku的优惠、满减信息    sms -> sms_sku_ladder
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                R r = couponFeignService.saveSkuReduction(skuReductionTo);
                if(r.getCode() != 0){
                    log.info("feign-saveSkuReduction调用失败!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`");
                }
            });

        }




    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();

        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.like(SpuInfoEntity::getSpuName,key);
        }

        String status = (String) params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq(SpuInfoEntity::getPublishStatus,status);
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isEmpty(brandId)){
            wrapper.eq(SpuInfoEntity::getBrandId,brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(brandId)){
            wrapper.eq(SpuInfoEntity::getCatalogId,catelogId);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void up(Long spuId) {

        //1、组装数据

        List<SkuInfoEntity> skus = skuInfoService.getSkuBySpuId(spuId);

        List<Long> skuIds = new ArrayList<>();
        for (SkuInfoEntity skuInfoEntity : skus) {
            skuIds.add(skuInfoEntity.getSkuId());
        }
        List<HasStockVo> vos = wareFeignService.hasStock(skuIds);
        Map<Long, Integer> map = vos.stream()
                .collect(Collectors.toMap(HasStockVo::getSkuId, HasStockVo::getStock));


        List<SkuEsModel> skuEsModelList = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();

            // sku相关信息  与 spuId
            skuEsModel.setSpuId(spuId);
            BeanUtils.copyProperties(sku, skuEsModel);

            //skuPrice  skuImage
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            // brandName brandImg   catalogName
            BrandEntity brand = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(category.getName());

            // attrs
            List<ProductAttrValueEntity> baseAttrs = productAttrValueService.listBySpuId(spuId);
            List<Long> attrIds = baseAttrs.stream().map(item -> {
                return item.getAttrId();
            }).collect(Collectors.toList());

            List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
            HashSet<Long> attrs = new HashSet<>(searchAttrIds);

            List<SkuEsModel.Attrs> collect = baseAttrs.stream().filter(item -> {
                return attrs.contains(item.getAttrId());
            }).map(item -> {
                SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
                BeanUtils.copyProperties(item, attrs1);
                return attrs1;
            }).collect(Collectors.toList());

            skuEsModel.setAttrs(collect);

            // hotscore
            //实际比较复杂，非重点，直接设置成零即可
            skuEsModel.setHotScore(0L);

            //hasstock
            Integer stock = map.get(sku.getSkuId());
            skuEsModel.setHasStock(stock>0?true:false);

            return skuEsModel;
        }).collect(Collectors.toList());

        //2. 发出请求，上架商品
        R r = searchFeignService.upProduct(skuEsModelList);
        if(r.getCode() == 0){
            //远程调用成功
            //修改上架状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //todo 重复调用 ， 也就是 接口幂等性
        }

    }

}